package com.example.es_demo.controller;

import com.example.es_demo.dao.CloudDiskDao;
import com.example.es_demo.entity.CloudDiskEntity;
import org.elasticsearch.index.query.*;
import org.elasticsearch.index.search.MultiMatchQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName PageController
 * @Description TODO
 * @Author zhaoluowei
 * @Date 2019/6/30  17:45
 * @Version 1.0
 */
@Controller
public class PageController {

    @Autowired
    private CloudDiskDao cloudDiskDao;

    /**
     * 可以加上方法的耗时时间 通过aop进行
     *
     * @param keyWord
     * @param pageable
     * @param request
     * @return
     */
    @RequestMapping(value = "/pageSearch")
    public String search(String keyWord, @PageableDefault(page = 0, value = 3) Pageable pageable, HttpServletRequest request) {
        long start = System.currentTimeMillis();

        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        if (!StringUtils.isEmpty(keyWord)) {
            MatchQueryBuilder matchQuery = QueryBuilders.matchQuery("name", keyWord);
            queryBuilder.must(matchQuery);
        }

        Page<CloudDiskEntity> page = cloudDiskDao.search(queryBuilder, pageable);
        long end = System.currentTimeMillis();


        // 计算查询总数
        long total = page.getTotalElements();
        request.setAttribute("total", page.getTotalElements());
        // 计算分页数
        int totalPage = (int) ((total - 1) / pageable.getPageSize() + 1);
        request.setAttribute("totalPage", totalPage);
        request.setAttribute("page", page);
        request.setAttribute("total", page.getTotalElements());
        request.setAttribute("time", (end - start));
        request.setAttribute("keyword",keyWord);
        return "search";
    }


}
